package test.shadow;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.content.Context;

import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
import org.robolectric.annotation.Resetter;
import org.robolectric.shadows.ShadowBluetoothDevice;

import test.util.Log;

import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR2;

@Implements(BluetoothDevice.class)
public class MyShadowBluetoothDevice extends ShadowBluetoothDevice {
    private static final String TAG = MyShadowBluetoothDevice.class.getSimpleName();

    private static ShadowUtil.MethodListener methodListener;
    private static BluetoothGatt gatt;
    private static BluetoothGattCallback gattCallback;

    @Resetter
    public static void resetMe() {
        Log.d(TAG, "resetMe");
        methodListener = null;
        gatt = null;
        gattCallback = null;
    }

    public static void setMethodListener(ShadowUtil.MethodListener listener) {
        methodListener = listener;
    }

    @Implementation
    protected boolean createBond() {
        if (methodListener != null) {
            String name = Thread.currentThread().getStackTrace()[1].getMethodName();
            Object[] parameters = null;
            Object ret = methodListener.onCallMethod(name, parameters);
            return ((boolean)ret);
        }

        return super.createBond();
    }

    @Implementation(minSdk = JELLY_BEAN_MR2)
    protected BluetoothGatt connectGatt(
            Context context, boolean autoConnect, BluetoothGattCallback callback) {
        gattCallback = callback;
        gatt = super.connectGatt(context, autoConnect, callback);

        if (methodListener != null) {
            String name = Thread.currentThread().getStackTrace()[1].getMethodName();
            Object[] parameters = new Object[] { context, autoConnect, callback };
            methodListener.onCallMethod(name, parameters);
        }

        return gatt;
    }

    public static BluetoothGatt getCurrentGatt() {
        return gatt;
    }

    public static BluetoothGattCallback getCurrentGattCallback() {
        return gattCallback;
    }
}
